package com.dwin.dingnuo.ui.base;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;


import com.dwin.dingnuo.R;
import com.dwin.dingnuo.http.beans.UserBean;
import com.dwin.dingnuo.utils.Constants;
import com.dwin.dingnuo.utils.ToastUtil;

import org.litepal.LitePal;

import java.util.List;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

/**
 * Fragment 基类
 */
public class BaseFragment extends Fragment {

    protected UserBean mUser;
    protected Context mContext;
    protected SharedPreferences logMessage = null; //用户日志保存
    protected String language = "zh";
    protected Resources mRes;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getActivity();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRes = getResources();
        mContext = getActivity();
        logMessage = getActivity().getSharedPreferences("logmessage", getActivity().MODE_PRIVATE);
        language = logMessage.getString("language", "zh");

        List<UserBean> list = LitePal.findAll(UserBean.class);
        if (list != null && list.size() > 0) {
            mUser = list.get(0); // 获取用户信息
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        List<UserBean> list = LitePal.findAll(UserBean.class);
        if (list != null && list.size() > 0) {
            mUser = list.get(0); // 获取用户信息
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            //非默认值
            ((BaseActivity) getActivity()).getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    public void userLogout() {
        ToastUtil.toastShort(mContext, getResources().getString(R.string.token_expired_login_again));
        LitePal.deleteAll(UserBean.class); // 先删除所有用户数据
/*        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TASK | intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);*/
    }

    public boolean onFragmentBackPressed() {
        return false;
    }

    protected <T extends View> T findView(@IdRes int id) {
        if (getView() != null) {
            return (T) getView().findViewById(id);
        }
        return null;
    }

    public boolean onActivityBackPressed() {
        return getBaseActivity().onActivityBackPressed();
    }

    public BaseActivity getBaseActivity() {
        return getActivity() != null ? (BaseActivity) getActivity() : null;
    }

    public void onFragmentResume() {
//        mUiHandler.setEnabled(true);
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    protected String getVersionName() {
        String version = null;
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(getActivity().getPackageName(), 0);
            version = info.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 权限检查方法
     *
     * @param permissions 权限数组
     * @return
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(getActivity(), permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    // 获得拍照，存储空间的访问权限
    public void doCameraPermission() {
    }

    // 父类提供默认的权限处理方法
    public void doSDCardPermission() {
    }

    /**
     * 提供权限请求方法
     *
     * @param code
     * @param permissions
     */
    public void requestPermissions(int code, String... permissions) {
        requestPermissions(permissions, code);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Constants.WRITE_EXTERNAL_CODE:
                doSDCardPermission();
                break;
            case Constants.CAMERA_CODE:
                doCameraPermission();
                break;
        }
    }

}
